use std::net::TcpListener;
use std::net::TcpStream;
use std::io::{Read, Write};
mod thread_pool;
use thread_pool::ThreadPool;
///启动服务器
pub fn start_server(){
    //Tcp绑定端口，返回监听器
    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
    println!("绑定端口成功");
    let thread_pool = ThreadPool::new(5);
    //遍历连接  //take(5)只处理5个连接
    for stream in listener.incoming().take(5) {
        //获取流
        let mut stream = stream.unwrap();

       thread_pool.execute(Box::new (move||{
            handle_conn(stream);
        }));
    }
}

///处理流 http协议格式
// GET / HTTP/1.1 #\r\n结尾
// Host: 127.0.0.1:7878
// Connection: keep-alive
// sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"
// sec-ch-ua-mobile: ?0
// Upgrade-Insecure-Requests: 1
// User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36
// Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
// Sec-Fetch-Site: none
// Sec-Fetch-Mode: navigate
fn handle_conn(mut stream: TcpStream) {
    //创建缓冲区
    let mut buf: [u8; 512] = [0; 512];
    //死循环，读取数据
    loop {
        //将数据读入缓冲区
        let size = stream.read(&mut buf).unwrap();
        if size == 0 { //连接关闭
            break;
        }
        //打印
        //println!("Request:{}", String::from_utf8_lossy(&buf[..size]));
        let content = String::from_utf8_lossy(&buf[..size]);

        //读取文件内容
        //let mut file = File::open("hello.html").unwrap();
        //let mut content = String::new();
        //let size = file.read_to_string(&mut content).unwrap();

        //响应
        let response = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",size, content);
        stream.write(response.as_bytes()).unwrap();
        stream.flush().unwrap();
    }
}